package com.codi.bus.core.service.impl;

import com.codi.base.util.BigDecimalUtil;
import com.codi.base.util.DateUtils;
import com.codi.base.util.StringUtil;
import com.codi.bus.core.dao.ScheduledDao;
import com.codi.bus.core.domain.Scheduled;
import com.codi.fcloud.ufx.UfxSDKFactory;
import com.codi.fcloud.ufx.constant.UrlConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 定投协议表操作类
 */
@Service
public class LocaldataScheduledService extends UfxSDKFactory {

    private static final Logger logger = LoggerFactory.getLogger(LocaldataScheduledService.class);
    @Autowired
    private ScheduledDao scheduledDao;
    /**
     * 定投协议申购时
     * @param bankAccount
     * @param userId
     * @param scheduledProtocolId
     */
    public void add(String bankAccount,String tradeAcco,long userId ,String scheduledProtocolId){

        try {
            //用户id、定投协议号、银行账号不能为空
            if(userId == 0 || StringUtil.isEmpty(scheduledProtocolId) || StringUtil.isEmpty(bankAccount)){
                logger.error("定投协议表操作类LocaldataScheduledService,定投协议变更时,用户id、定投协议号、银行账号不能为空,当前用户={}",userId);
                return;
            }
            Map<String , Object> request = new HashMap<>();
            request.put("request_num",DEF_MAX_REQUEST_NUM);
            request.put("scheduled_protocol_id",scheduledProtocolId);
            //调用恒生接口查询
            List<Map<String, Object>> response = getUfxSDK().query(getTarget(), request);
            //根据是否成功判断
            String successType = response.get(0).get("success_type").toString();
            if (successType.equals("1")) {
                logger.error("定投协议表操作类LocaldataScheduledService add方法:1-系统级错误,当前用户={}",userId);
                return;
            } else if (successType.equals("2")) {
                logger.error("定投协议表操作类LocaldataScheduledService add方法:2-应用级错误,当前用户={}",userId);
                return;
            } else if (successType.equals("3")) {
                logger.error("定投协议表操作类LocaldataScheduledService add方法:3-业务级错误,当前用户={}",userId);
                return;
            }
            //根据返回的记录数判断
            String rowCount = response.get(0).get("rowcount").toString();
            if(StringUtil.isEmpty(rowCount)){
                logger.error("定投协议表操作类LocaldataScheduledService，定投协议申购时插入数据失败，返回的记录数为空，,当前用户={}，scheduledProtocolId={}",userId,scheduledProtocolId);
                return;
            }
            for (Map<String, Object> map : response) {

                String protocolFixDay = map.get("protocol_fix_day").toString();
                String balance = map.get("balance").toString();
                String protocolPeriodUnit = map.get("protocol_period_unit").toString();
                String fixState = map.get("fix_state").toString();//正常（A）；终止（H）；暂停（P）；

                Scheduled scheduled = new Scheduled();
                scheduled.setUserId(new Long(userId).intValue());
                scheduled.setScheduledProtocolId(scheduledProtocolId);
                scheduled.setBankAccount(bankAccount);
                scheduled.setBankName(tradeAcco);
                scheduled.setProtocolPeriodUnit(protocolPeriodUnit);
                scheduled.setTradePeriod(protocolFixDay); //这里要存定投交易日  数据库中是交易周期
                scheduled.setIsValid(fixState);
                scheduled.setBalance(BigDecimalUtil.ConvertToBigDecimal(balance));

                scheduledDao.insert(scheduled);
            }
        } catch (Exception e) {
            logger.error("定投协议表操作类LocaldataScheduledServiced  定投协议申购时本地化数据失败！当前用户={}",userId);
            e.printStackTrace();
        }
    }

    /**
     * 定投协议变更时
     * @param bankAccount
     * @param userId
     * @param scheduledProtocolId
     */
    public void update(long userId ,String scheduledProtocolId ,String bankAccount,String tradeAcco){

        try {
            //用户id、定投协议号、银行账号不能为空
            if(userId == 0 || StringUtil.isEmpty(scheduledProtocolId) || StringUtil.isEmpty(bankAccount)){
                logger.error("定投协议表操作类LocaldataScheduledService,定投协议变更时,用户id、定投协议号、银行账号不能为空,当前用户={}",userId);
                return;
            }
            Map<String , Object> request = new HashMap<>();
            request.put("request_num",DEF_MAX_REQUEST_NUM);
            request.put("scheduled_protocol_id",scheduledProtocolId);
            //调用恒生接口查询
            List<Map<String, Object>> response = getUfxSDK().query(getTarget(), request);
            //根据是否成功判断
            String successType = response.get(0).get("success_type").toString();
            if(successType.equals("1")){
                logger.error("定投协议表操作类LocaldataScheduledService update方法:1-系统级错误,当前用户={}",userId);
                return;
            }else if (successType.equals("2")){
                logger.error("定投协议表操作类LocaldataScheduledService update方法:2-应用级错误,当前用户={}",userId);
                return;
            }else if (successType.equals("3")){
                logger.error("定投协议表操作类LocaldataScheduledService update方法:3-业务级错误,当前用户={}",userId);
                return;
            }
            //根据返回的记录数判断
            String rowCount = response.get(0).get("rowcount").toString();
            if(StringUtil.isEmpty(rowCount)){
                logger.error("定投协议表操作类LocaldataScheduledService，定投协议变更时插入数据失败,查询返回的记录数为空，,当前用户={}，scheduledProtocolId={}",userId,scheduledProtocolId);
                return;
            }
            for (Map<String, Object> map : response) {

                String protocolFixDay = map.get("protocol_fix_day").toString();
                String balance = map.get("balance").toString();
                String protocolPeriodUnit = map.get("protocol_period_unit").toString();
                String fixState = map.get("fix_state").toString();//正常（A）；终止（H）；暂停（P）；

                Scheduled scheduled = new Scheduled();
                scheduled.setUserId(new Long(userId).intValue());
                scheduled.setScheduledProtocolId(scheduledProtocolId);
                scheduled.setBankAccount(bankAccount);
                scheduled.setBankName(tradeAcco);
                scheduled.setProtocolPeriodUnit(protocolPeriodUnit);
                scheduled.setTradePeriod(protocolFixDay);
                scheduled.setIsValid(fixState);
                scheduled.setBalance(BigDecimalUtil.ConvertToBigDecimal(balance));
                //获取要修改的定投协议
                Scheduled scheduled1 = scheduledDao.selectByScheduledProtocolId(scheduledProtocolId);
                scheduled.setScheduledId(scheduled1.getScheduledId());

                scheduledDao.updateByPrimaryKeySelective(scheduled);

            }
        } catch (Exception e) {
            logger.error("定投协议表操作类LocaldataScheduledServiced  update定投协议变更时本地化数据失败！当前用户={}",userId);
            e.printStackTrace();
        }

    }

    /**
     * 获取当天要发生的定投协议
     * @param date
     * @return
     */
    public List<Scheduled> getScheduledProtocolId(Date date){
        List<Scheduled> list = new ArrayList<>();
        try {
            if(StringUtil.isEmpty(date.toString())){
                logger.error("定投协议表操作类LocaldataScheduledServiced  getScheduledProtocolId获取当天要发生的定投协议失败！日期date不能为空");
                return null;
            }
            String s = DateUtils.formatDate4(date);
            //当月的那一天
            String monthDay = s.substring(6); // 01 05 11 24
            //每周的周几
            String weekDay = "";
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);
            int i =calendar.get(Calendar.DAY_OF_WEEK);
            if(i == 1){
                weekDay = "7";
            }else{
                weekDay = i+""; // 2为周一
            }
            //存放scheduledProtocolId
            List<Scheduled> all = scheduledDao.findListByIsValid("A"); //正常（A）；终止（H）；暂停（P）；
            if(all == null || all.size() == 0){
                return list;
            }
            for (Scheduled scheduled : all) {
                //月
                if(scheduled.getProtocolPeriodUnit().equals("0")){
                    if(monthDay.equals(scheduled.getTradePeriod())){
                        list.add(scheduled);
                    }
                //周
                }else if(scheduled.getProtocolPeriodUnit().equals("1")){
                    if(weekDay.equals(scheduled.getTradePeriod())){
                        list.add(scheduled);
                    }
                }
            }

            return list;
        } catch (Exception e) {
            logger.error("定投协议表操作类LocaldataScheduledServiced  getScheduledProtocolId获取当天要发生的定投协议失败!");
            e.printStackTrace();
        }
        return list;
    }
    @Override
    protected String getTarget() {
        return UrlConstants.PREFIX_SALE + UrlConstants.FIX_QRY;
    }
}
